import { Injectable } from '@nestjs/common';
import { CreateUserBehaviorDto } from './dto/create-user-behavior.dto';
import { UpdateUserBehaviorDto } from './dto/update-user-behavior.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Raw, Repository } from 'typeorm';

import { UserBehavior } from './entities/user-behavior.entity';
import { QueryDto } from './dto/query.dto';
import { UserInfoDto } from '../model/dto/user-info.dto';
@Injectable()
export class UserBehaviorService {

  constructor(
    @InjectRepository(UserBehavior) private readonly userBehaviorRepository: Repository<UserBehavior>,
  ) {

  }
  async create(createuserBehaviorDto: CreateUserBehaviorDto, user?: UserInfoDto) {

    const exit = await this.userBehaviorRepository.findOneBy({
      name: createuserBehaviorDto.name,
      userId: user?.id

    });

    if (exit) {
      return {
        code: 400,
        data: null,
        message: '数据已存在',
      };
    }
    const userBehavior = this.userBehaviorRepository.create({
      ...createuserBehaviorDto,
      type: 'personal',
      userId: user?.id,
      action: {
        likes: 0,
        collects: 0,
        uses: 0,
      }
    });
    const savedBehavior = await this.userBehaviorRepository.save(userBehavior);
    return {
      code: 200,
      data: {
        id: savedBehavior.id,
        name: savedBehavior.name,
        type: savedBehavior.type
      },
      message: '创建成功'
    };
  }
  async findAll(query: QueryDto) {
    const { pageNum = 1, pageSize = 10, keywords = '', ...rest } = query;
    const [result, total] = await this.userBehaviorRepository.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      where: {
        ...rest,
        name: keywords ?
          Raw(alias =>
            `${alias} REGEXP :pattern OR description REGEXP :pattern`,
            { pattern: keywords.replace(/,/g, '|') }
          ) :
          Like('%')
      },
    });

    return {
      rows: result,
      total
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} userBehavior`;
  }

  update(id: number, updateUserBehaviorDto: UpdateUserBehaviorDto) {
    return `This action updates a #${id} userBehavior`;
  }

  remove(id: number) {
    return `This action removes a #${id} userBehavior`;
  }
}
